/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.google.code.jmarias.client.tcp;

import com.google.code.jmarias.common.action.AbstractAction;
import com.google.code.jmarias.common.action.ChooseDurchAction;
import com.google.code.jmarias.common.action.PickCardFromPeopleAction;
import java.util.HashSet;
import java.util.Set;

/**
 *
 * @author Ondrej Michal &lt;ondrej.michal@netvoice.cz&gt;
 */
public class NewClass2  {

    private static Set<ActionListener> listeners = new HashSet<ActionListener>();

    private String state = "";

    static {
        addListener(new ActionListener(PickCardFromPeopleAction.class) {

            @Override
            public void processAction(AbstractAction action, String state) {
                System.out.println("volim z lidu");
            }
            
        });
        addListener(new ActionListener(ChooseDurchAction.class) {

            @Override
            public void processAction(AbstractAction action, String state) {
                System.out.println("hraju durch, stav je " + state);
            }
            
        });
    }


    private static void addListener(ActionListener listener) {
        listeners.add(listener);
    }

    /** Musi vyhovovat jen jeden listener, jinak konci vyjimkou. */
    public void processAction(AbstractAction action) {
        int i = 0;
        for (ActionListener listener : listeners) {
            if (listener.accepts(action)) {
                i++;
                if (i > 1) {
                    throw new RuntimeException("Chyba serveru - akci " + action + " zpracovava vice listeneru.");
                }
                listener.actionPerformed(action, state);
            }
        }
        if (i == 0) {
            System.out.println("Akce nebyla zachycena zadnym listenerem, zrejme tedy slo o nepovolenou akci, a proto byla ignorovana.");
        }
    }

    private abstract static class ActionListener {

        public void actionPerformed(AbstractAction action, String state) {
            processAction(action, state);
        }

        protected abstract void processAction(AbstractAction action, String state);

        private Class acceptedAction;

        public ActionListener(Class acceptedAction) {
            this.acceptedAction = acceptedAction;
        }

        public boolean accepts(AbstractAction action) {
            return acceptedAction.isAssignableFrom(action.getClass());
        }

        @Override
        public String toString() {
            return "listener " + acceptedAction;
        }

    }
    
    public static void main(String[] args) {
//        new NewClass().processAction(null);
//        new NewClass().processAction(null);
        System.out.println(NewClass2.listeners);

        NewClass2 clazz = new NewClass2();
        clazz.state = "stav1";
        clazz.processAction(new ChooseDurchAction());
    }
}
